# Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import time
import sys

import torch

import opts
sys.path.append(r"./BMN-Boundary-Matching-Network")
from models import BMN


def tar2onnx(opt):
    input_file = opt['input_file']
    output_file = opt['output_file']
    batch_size = opt['infer_batch_size']
    opset_version = opt['opset_version']
    verbose = opt['verbose']
    feat_dim = opt['feat_dim']
    temporal_scale = opt['temporal_scale']

    # 1. Create model
    print('Model checkpoint path is:', os.path.abspath(opt['input_file']))
    model = BMN(opt)
    checkpoint = torch.load(input_file, map_location=torch.device('cpu'))['state_dict']

    # 2. rm 'module.', load state_dict
    state_dict = dict()
    for k in checkpoint:
        assert k.startswith('module.')
        state_dict[k[7:]] = checkpoint[k]

    model.load_state_dict(state_dict)
    model.eval()

    # 3. Export as onnx
    assert feat_dim, temporal_scale == [400, 100]
    dummy_input = torch.randn(batch_size, feat_dim, temporal_scale)
    input_names = ['image']
    output_names = ['confidence_map', 'start', 'end']
    start_time = time.time()
    torch.onnx.export(
        model, 
        dummy_input, 
        output_file, 
        input_names=input_names, 
        output_names=output_names, 
        opset_version=opset_version, 
        verbose=verbose
        )
    print('Onnx convertion takes time: {}(s)'.format(time.time()-start_time))

if __name__=="__main__":
    option = opts.parse_opt()
    option = vars(option) 
    tar2onnx(option)
